#!/usr/bin/env python
# coding=utf-8

from vavava.workqueue import Work
from . import track_db
import sys

class TaskWorkBase(Work):
    def __init__( self, track_type, period, group, begin_time=None, end_time=None, log=None,**kargs ):
        Work.__init__( self,period=period, group=group, begin_time=begin_time, end_time=end_time, log=log, name="" )
        self.track_type_      = track_type
        self.timeout_items_   = {}
        self.delivered_items_ = {}
        self.tracking_items_  = {}
        self.proxy_           = None
        if kargs is not None and "proxy" in kargs:
            self.proxy_ = kargs["proxy"]
        self.redo_counter_ = sys.maxsize

    def _get_all_items(self):
        """ method to get all items """
        pass

    def _get_work_instance(self, itemID):
        """ method to get work instance """
        assert(False)

    def do(self,worker):
        if not worker:
            raise Exception( "[%s] Unknown parent,cannot add work for main task. " % self._name )
        if worker._db_conn is None:
            raise Exception( "[%s] DBObj is Null." % self._name )
        try:
            self._main_routine(worker)
        except Exception as e:
            self.log.error( "[%s] exception in _main_routine", self._name )
            self.log.exception(e)
        self.redo_counter_ -= 1
        if self.redo_counter_ > 0:
            self._done = False # need start again
        else:
            self._done = True # do not need start again
        self.log.info("[%s] AddTrackWork ended. [redo=%d,work_done=%s,period=%f]"
            ,self._name,self.redo_counter_, str(self._done), self._period )

    def _main_routine(self,worker):
        self.log.info("[%s] AddTrackWork begin. [redo=%d,work_done=%s]", self._name,self.redo_counter_, str(self._done) )
        # get data from db
        db = track_db.TrackDB(db_conn=worker._db_conn,log=self.log)
        self.tracking_items_  = db.get_tracking_items(self.track_type_)
        self.delivered_items_ = db.get_delivered_items(self.track_type_)
        self.timeout_items_   = db.get_timeout_items(self.track_type_)
        self.log.info("[%s] Get db data:[tracking=%d,delivered=%d,timeout_items_=%d]",
            self._name,len(self.tracking_items_),len(self.delivered_items_),len(self.timeout_items_) )
        # get items from web
        all_items = self._get_all_items( )
        if all_items is None:
            all_items = self.tracking_items_
            self.log.warn("[%s]Failed to get item list from web.", self._name )
            # process data
        new_items_count = 0
        for item in all_items:
            tmp_dict={}
            if item in self.delivered_items_:
                continue
            if item in self.timeout_items_:
                continue
            if item not in self.tracking_items_:
                self.delivered_items_[item] = ""
                self.log.info( "[%s] New item:%s",self._name, item)
                new_items_count += 1
            # add to workshop
            work = self._get_work_instance( item_id=item )
            worker._wq_parent.QueueWork(work=work)
            if not worker.IsRunning:
                self.log.debug("[%s] user canceled. Item=%s",self._name,item)
                return
            self.log.debug("[%s] Add db work to workshop. Item=%s",self._name,item)
        self.log.info("[%s] new_items_size=%d,tracking_items_=%d", self._name,new_items_count,len(self.tracking_items_))















